package com.lfg.leetcode.leetcode500;


import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class No846isNStraightHand {
    public static void main(String[] args) {
        System.out.println(isNStraightHand(new int[]
                {8,10,12}, 3));
    }

    public static boolean isNStraightHand(int[] hand, int groupSize) {
        if (hand.length % groupSize != 0) {
            return false;
        }
        Arrays.sort(hand);
        Map<Integer, Integer> count = new HashMap<>(hand.length);
        for (int i : hand) {
            Integer cnt = count.get(i);
            if (cnt == null) {
                count.put(i, 1);
            } else {
                count.put(i, cnt + 1);
            }
        }
        for (int i = 0; i < hand.length; ) {
            int start = hand[i];
            if(!count.containsKey(start)){
                i++;
                continue;
            }

            for (int j = 0; j < groupSize; j++) {
                Integer cnt = count.get(start);
                if(cnt == null){
                    return false;
                }
                if (cnt == 1) {
                    count.remove(start);
                } else {
                    count.put(start, cnt - 1);
                }
                start++;
            }
        }
        return count.isEmpty();
    }
}

